package com.ilop.siteraudio.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.ilop.siteraudio.R;
import com.ilop.siteraudio.adapter.SendReportAdapter;
import com.ilop.siteraudio.base.LoadingDialog;
import com.ilop.siteraudio.data.bean.EmailBean;
import com.ilop.siteraudio.data.bean.ReportBean;
import com.ilop.siteraudio.data.util.EmailDaoUtil;
import com.ilop.siteraudio.data.util.ReportDaoUtil;
import com.ilop.siteraudio.util.CustomToastUtil;
import com.ilop.siteraudio.util.StatusBarUtil;
import com.ilop.siteraudio.util.okhttp.OkHttpClientUtils;
import com.ilop.siteraudio.util.okhttp.OnHttpResponseCallBack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Response;

/**
 * @author skygge
 * @date 2/4/21.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class SendReportActivity extends AppCompatActivity{

    private static final String TAG = SendReportActivity.class.getSimpleName();

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.iv_send_back)
    ImageView mReportSendBack;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.report_add_email)
    ImageView mAddEmail;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.bt_send_email)
    Button mSendEmail;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.email_recycle)
    RecyclerView mReportEmailList;

    private List<String> mEmailAddress;
    private ArrayList<Integer> mRecordIdList;
    private List<ReportBean> mReportList;
    private SendReportAdapter mAdapter;

    private LoadingDialog mDialog;
    private Handler mHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_report);
        StatusBarUtil.setDefaultStatus(this);
        ButterKnife.bind(this);
        mRecordIdList = getIntent().getIntegerArrayListExtra("recordIdList");
        initView();
        initData();
        initListener();
    }

    private void initView() {
        mEmailAddress = new ArrayList<>();
        mReportList = new ArrayList<>();
        mReportEmailList.setLayoutManager(new LinearLayoutManager(this));
        List<EmailBean> emailList = EmailDaoUtil.getInstance().getEmailDao().queryAll();
        mAdapter = new SendReportAdapter(this, emailList);
        mReportEmailList.setAdapter(mAdapter);
    }

    private void initData() {
        for (Integer id:mRecordIdList) {
            ReportBean mReportBean = ReportDaoUtil.getInstance().getReportById(id);
            mReportList.add(mReportBean);
        }
    }

    private void initListener() {
        mReportSendBack.setOnClickListener(view -> finish());
        mAddEmail.setOnClickListener(view -> mAdapter.onAddNewEmail());
        mSendEmail.setOnClickListener(view -> {
            mEmailAddress = mAdapter.getEmailAddressList();
            sendEmailMessage();
        });
    }

    private String getEmailMessage() {
        if (mEmailAddress.size() == 0) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("emails", mEmailAddress);
        map.put("reportList", mReportList);
        return JSON.toJSONString(map);
    }

    private void sendEmailMessage(){
        String message = getEmailMessage();
        if (message == null) {
            CustomToastUtil.showToast(this, getString(R.string.email_address_empty));
            return;
        }
        mDialog = new LoadingDialog(this);
        mDialog.show();
        mHandler = new Handler(Looper.getMainLooper());
        new Thread() {
            @Override
            public void run() {
                super.run();
                String url = "http://61.164.94.198:16802/siteraudio/sf/sendMail";
                Log.i(TAG, "recordIdList: " + message);
                OkHttpClientUtils.getInstance().onPostMessage(url, message, new OnHttpResponseCallBack() {
                    @Override
                    public void onSuccessful(Response response) {
                        sendEmailResult(true);
                    }

                    @Override
                    public void onFailure() {
                        sendEmailResult(false);
                    }
                });
            }
        }.start();
    }

    private void sendEmailResult(boolean isSuccess) {
        String toast = getString(isSuccess ? R.string.sent_successfully : R.string.send_fail);
        mHandler.postDelayed(() -> {
            mDialog.dismiss();
            CustomToastUtil.showToast(SendReportActivity.this, toast);
            if (isSuccess) {
                finish();
            }
        }, 800);
        if (isSuccess) {
            for (String email:mEmailAddress) {
                EmailBean emailBean = new EmailBean();
                emailBean.setEmail(email);
                EmailDaoUtil.getInstance().getEmailDao().insertOrReplace(emailBean);
            }
        }
    }
}
